package com.ujiuye.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ujiuye.pojo.DataCollect;
import com.ujiuye.service.DataCollectService;
import com.ujiuye.utils.MyFileUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.List;

@RestController
@RequestMapping("/datacollect")
public class DataCollectController {
    @Autowired
    private DataCollectService dataCollectService;

    @RequestMapping("/list")
    public PageInfo<DataCollect> list(
            @RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum){
        try {
            PageHelper.startPage(pageNum,3);
            List<DataCollect> list = dataCollectService.list();
            PageInfo<DataCollect> pageInfo = new PageInfo<>(list);
            return pageInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/get")
    public DataCollect get(int id){
        try {
            return dataCollectService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/save")
    public String save(DataCollect dataCollect){
        try {
            dataCollectService.save(dataCollect);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    @RequestMapping("/update")
    public String update(DataCollect dataCollect){
        try {
            dataCollectService.update(dataCollect);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    @RequestMapping("/remove")
    public String remove(int id){
        try {
            dataCollectService.remove(id);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    @RequestMapping("/removeList")
    public String removeAll(Integer[] ids){
        try {
            dataCollectService.removeAll(ids);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

    @RequestMapping("/downLoadExcel")
    public ResponseEntity<byte[]> downLoad(
            @RequestParam(value = "pageNum",required = false,defaultValue = "1") int pageNum
    ){
        File file = dataCollectService.getDownloadFile(pageNum);
        return MyFileUtils.download(file);
    }
}
